'use strict'
import router from '../router'
import axios from 'axios'
import util from './util'
import * as api from './api'
import store from '../store'
// import dataStore from '../data'

// 服务器地址
axios.defaults.baseURL = 'http://antegg.net:8080/api'
// axios.defaults.baseURL = 'http://192.168.1.13:80/api'
axios.defaults.withCredentials = true // 带上cookie

const CancelToken = axios.CancelToken
const source = CancelToken.source()
// 请求拦截
axios.interceptors.request.use(config => {
  // 需要鉴权的协议
  var AuthRequestList = [
    api.protoIdCommentReq,
    api.protoIdFavoriteReq,
    api.protoIdFollowReq,
    api.protoIdGetUploadTokenReq,
    api.protoIdPraiseReq,
    api.protoIdSearchReq,
    api.protoIdWriteArticleReq
  ]
  console.log('==========REQ', config.data)
  let pkg = JSON.parse(config.data)
  // 鉴权协议需要登录
  if (AuthRequestList.includes(pkg.pid)) {
    if (!store.getters.GetUserToken) {
      config.cancelToken = source.token
      // 跳转至登录界面
      router.push('/login')
      source.cancel()
      return Promise.reject(new Error('请先登录哦'))
    }
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 返回拦截
axios.interceptors.response.use(res => {
  console.log('==========ACK', res.data)
  return util.decode(res.data)
}, error => {
  console.log('error===========', error)
  if (axios.isCancel(error)) { // 取消请求的情况下，终端Promise调用链
    return new Promise(() => {})
  } else {
    return Promise.reject(error)
  }
})

export default axios
